package com.cll.learn.cas.demo02;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2021/5/15 12:05
 */
public class AtomicStampedReferenceDemo {

    static AtomicStampedReference<Integer> money = new AtomicStampedReference<>(19, 0);

    public static void main(String[] args) {
        // 重置线程
        for (int i = 0; i < 3; i++) {
            final int stamp = money.getStamp();
            new Thread(){
                @Override
                public void run() {
                    while (true) {
                        while (true) {
                            Integer m = money.getReference();
                            if (m < 20) {
                                if (money.compareAndSet(m, m+ 20, stamp, stamp+1)) {
                                    System.out.println("===>>> 余额小于20.当前余额 = " + m + ":重置之后余额"  + money.getReference());
                                    break;
                                }
                            } else {
                                break;
                            }
                        }
                    }
                }
            }.start();
        }

        // 1个消费线程
        new Thread(){
            @Override
            public void run() {
                // 保持持续消费100次
                for (int i = 0; i < 100; i++) {
                    while (true) {
                        int stamp = money.getStamp();
                        Integer m = money.getReference();
                        if (m > 10) {
                            System.out.println("===>>> 大于10元");
                            if (money.compareAndSet(m, m - 10, stamp, stamp + 1)) {
                                System.out.println("===>>> 消费成功。余额 = " + money.getReference());
                                break;
                            }
                        } else {
                            System.out.println("===>>> 余额不足");
                            break;
                        }
                    }

                    // 100毫秒消费一次
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

                    }
                }
            }
        }.start();
    }
}
